/*
 * @Author: wangming
 * @Date: 2022-03-10 15:00:55
 * @LastEditors: wangming
 * @LastEditTime: 2022-03-31 10:41:37
 * @FilePath: /hanma-application-designer-fed/src/i18n.js
 * @Description: 
 */
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import stores from "store2";
import {
  getHmi18ninfoListByLanguage
} from "@/apis/paas/HmI18nInfoController.js";
import {
  getHmi18nlocaleList
} from "@/apis/paas/HmI18nLocaleController.js";
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
import jaLocale from 'element-ui/lib/locale/lang/ja'
import TWLocale from 'element-ui/lib/locale/lang/zh-TW'
import koLocale from 'element-ui/lib/locale/lang/ko'
import ruLocale from 'element-ui/lib/locale/lang/ru-RU'
import ElementLocale from 'element-ui/lib/locale'
const el_i18n = {
  'ko-KR': koLocale,
  'ja-JP': jaLocale,
  'en-US': enLocale,
  'zh-CN': zhLocale,
  'zh-TW': TWLocale,
  'ru-RU': ruLocale,
}
Vue.use(VueI18n)
function loadLocaleMessages() {
  const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
  const messages = {}
  locales.keys().forEach(key => {
    const matched = key.match(/([A-Za-z0-9-_]+)\./i)
    if (matched && matched.length > 1) {
      const locale = matched[1]
      messages[locale] = locales(key)
    }
  })
  return messages
}
export function getLangforlocale() {
  if (process.env.VUE_APP_USER === 'APP') {
    return stores.get("APP_LANG") || 'sys_CN'
  } else {
    return 'sys_CN'
  }
}
const i18n = new VueI18n({
  locale: getLangforlocale(),
  fallbackLocale: 'sys_CN',
  formatFallbackMessages: true,
  silentTranslationWarn: true,
  messages: loadLocaleMessages()
})
export default i18n

export class CliI18n {
  static defaultlang = null // 默认语言
  static defaultJson = null   // 默认语言json
  static langList = []   // 初始化语言包
  static async i18nInit() {
    if (process.env.VUE_APP_USER === 'ADMIN') return
    this.langList = await getHmi18nlocaleList()
    //获取默认语言
    this.defaultlang = this.langList.find(item => item.status === "DEFAULT")?.key
    //获取默认语言json
    this.defaultJson = await getHmi18ninfoListByLanguage({ language: this.defaultlang }, { langJson: this.defaultlang })
    const storeLang = stores.get('APP_LANG')
    let inlangs = this.langList.find(item => item.key === storeLang)
    let lang = inlangs ? storeLang : this.defaultlang
    try {
      await this.changeLang(lang)
    } catch (error) { }
  }
  static async changeLang(lang) {
    var json = this.defaultJson
    if (lang !== this.defaultlang) {
      let langjson = await getHmi18ninfoListByLanguage({
        language: lang
      }, { langJson: lang });
      json = { ...json, ...langjson }
    }
    for (const key in json) {
      json[key] = json[key] || undefined
    }
    i18n.setLocaleMessage(lang, { ...json, ...(el_i18n[lang]) })
    i18n.locale = lang;
    stores.set("APP_LANG", lang);
    ElementLocale.i18n((key, value) => i18n.t(key, value))
  }
}

